package com.tuzhi.testjpa;

import com.tuzhi.util.ListTzUtil;
import org.hibernate.query.internal.NativeQueryImpl;
import org.hibernate.transform.Transformers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Component
public class TestJpaEmImpl {


    private static final Logger log = LoggerFactory.getLogger(com.tuzhi.base.jpa.repository.impl.CommonRepoImpl.class);

//    @PersistenceContext(unitName = "secondaryEntityManagerFactory")
    @PersistenceContext(unitName = "secondaryPersistenceUnit")
    private EntityManager entityManager;


    @Transactional(readOnly = true)
    public Object findSingleResultBySql(String sql, Object... params) {

        sql = "select username from sys_user where id=1?";

//        Query query = entityManager.createNativeQuery("select username from sys_user where id=1");
//        Object obj = query.getSingleResult();
//        System.out.println(obj);
        List list = findOneColBySql(sql, params);
        if (ListTzUtil.isNotEmpty(list)) {
            return list.get(0);
        }
        return null;
    }

    public List findOneColBySql(String sql, Object... params) {
        List<Map> list = findAllMapBySql(sql, params);
        return transOneColList(list);
    }


    public <T> List<T> findAllMapBySql(String sql, Object... params) {
        Query query = entityManager.createNativeQuery(sql);
        setParams(query, params);
        query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        return query.getResultList();
    }

    private void setParams(Query query, Object... params) {
        if (params != null) {
            for (int i = 0; i < params.length; i++) {
                query.setParameter(i+1, params[i]);
            }
        }
    }

    private List transOneColList(List<Map> list) {
        if (ListTzUtil.isNotEmpty(list)) {
            List rs = new ArrayList();
            list.stream().forEach((Map map) ->{
                Iterator iterator = map.values().iterator();
                rs.add(iterator.next());
            });
            return rs;
        }
        return null;
    }

}
